//
//  NetworkSessionManager.m
//  SLDemo
//
//  Created by bocai on 2016/12/5.
//  Copyright © 2016年 Heracles. All rights reserved.
//

#import "NetworkSessionManager.h"
#import "CodeManager.h"
#import "PrintManager.h"

@implementation NetworkSessionManager

- (void)requestWithAPI:(NetworkBaseAPI *)api
         callbackBlock:(NetworkSessionCallbackBlock)callbackBlock
{
    //  输出类型
    __block NetworkPrintType printType;
    //  根据拓展参数合成parameters和urlString
    NSDictionary *parameters = [api transformParameters];
    NSString *urlString = [api transformURLString];
    
    //  根据加密方式对请求参数进行加密
    parameters = [[CodeManager sharedManager] encodeNetworkRequestParameters:parameters encodeMethod:api.encodeMethod];
    
    //  共同block回调
    id commonCallbackBlock =^(id responseObject, NSProgress *progress, NSError *error) {
        //  连接上服务器
        if (!error) {
            //  请求过程，回调progress
            if (progress) {
                callbackBlock(nil, progress, nil);
                printType = NetworkPrintProgressType;
            }
            //  请求完成，回调responseModel
            else {
                //  根据解密方式对服务器返回对象解密
                id decodeObject = [[CodeManager sharedManager] decodeNetworkResponseObject:responseObject decodeMethod:api.decodeMethod];
                NetworkResponseModel *responseModel = [NetworkResponseModel mj_objectWithKeyValues:decodeObject];
                callbackBlock(responseModel, nil, nil);
                printType = NetworkPrintResponseModelType;
            }
        }
        //  没有连接上服务器，回调error
        else {
            callbackBlock(nil, nil, error);
            printType = NetworkPrintErrorType;
        }
        //  打印网络请求信息
        NSString *printString = [[PrintManager sharedManager] printStringFromNetworkAPI:api printType:printType];
        NSLog(@"%@", printString);
    };
    
    //  上传网络请求
    if (api.uploadModel) {
        [self uploadDatasWithURLString:urlString parameters:api.parameters datas:api.uploadModel.datas name:api.uploadModel.name fileNames:api.uploadModel.fileNames mimeType:api.uploadModel.mimeType callbackBlock:commonCallbackBlock];
    }
    //  普通网络请求
    else {
        [self requestWithURLString:urlString httpMethod:api.httpMethod parameters:parameters callbackBlock:commonCallbackBlock];
    }
}

@end
